package com.dsteiner.gwt.cafeteriasophia.client.controller;

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.List;

import com.dsteiner.gwt.cafeteriasophia.client.domain.ShiftChange;
import com.dsteiner.gwt.cafeteriasophia.client.model.HistoryModel;
import com.dsteiner.gwt.cafeteriasophia.client.model.ShiftChangeInfoModel;
import com.dsteiner.gwt.cafeteriasophia.client.rpc.DataService;
import com.dsteiner.widgets.client.Widgets.IFlowPanel;
import com.dsteiner.widgets.client.Widgets.ILazyWidget;
import com.dsteiner.widgets.client.Widgets.IWidget;
import com.dsteiner.widgets.client.Widgets.IWidgetBuilder;
import com.dsteiner.widgets.client.Widgets.WidgetListenerAdapter;
import com.dsteiner.widgets.client.domain.Sort;
import com.dsteiner.widgets.client.rpc.SearchRequest;
import com.dsteiner.widgets.client.rpc.SearchResult;
import com.dsteiner.widgets.client.rpc.SearchRequest.SearchRequestImpl;
import com.google.gwt.user.client.rpc.AsyncCallback;

public class HistoryController {

	private HistoryModel historyModel;
	private IWidgetBuilder widgetBuilder;
	private IFlowPanel contentPanel;

	public void registerHistoryWidget(ILazyWidget historyWidget) {
		historyWidget.addWidgetListener(new WidgetListenerAdapter() {
			@Override
			public void onAttach(IWidget widget) {
				loadShiftChanges();
			}
		});
	}

	private void loadShiftChanges() {
		SearchRequestImpl searchRequest = new SearchRequestImpl();
		Sort sort = new Sort("date", false);
		searchRequest.setClassName(ShiftChange.class.getName());
		searchRequest.setLimit(20);
		searchRequest.setOffset(0);
		searchRequest.setSort(sort);
		searchRequest.setType(SearchRequest.TYPE_ALL);
		DataService.Util.getInstance().search(searchRequest, new AsyncCallback<SearchResult<ShiftChange>>(){
			public void onFailure(Throwable caught) {
				caught.printStackTrace();
			}
			public void onSuccess(SearchResult<ShiftChange> result) {
				historyModel.setShiftChanges(result.getObjects());
			}
		});
	}

	public void registerHistoryModel(HistoryModel historyModel) {
		this.historyModel = historyModel;
		historyModel.addPropertyChangeListener("shiftChanges", new PropertyChangeListener(){
			public void propertyChange(PropertyChangeEvent evt) {
				updateShiftChanges();
			}
		});
	}

	private void updateShiftChanges() {
		List<ShiftChange> shiftChanges = historyModel.getShiftChanges();
		contentPanel.clear();
		for (ShiftChange shiftChange : shiftChanges) {
			ShiftChangeInfoModel shiftChangeInfoModel = new ShiftChangeInfoModel();
			shiftChangeInfoModel.setShiftChange(shiftChange);
			IWidget widget = widgetBuilder.createWidget(shiftChangeInfoModel);
			contentPanel.add(widget);
		}
	}

	public void registerWidgetBuilder(IWidgetBuilder widgetBuilder) {
		this.widgetBuilder = widgetBuilder;
	}

	public void registerContentPanel(IFlowPanel contentPanel) {
		this.contentPanel = contentPanel;
	}
}